package com.java.jvm.demo.chapter01;

import java.io.FileNotFoundException;

/**
 * @author wangning
 * @create 2021-10-14 20:26
 */
public class CustomClassLoader extends ClassLoader {

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		try {
			byte[] result = getClassFromCustomPath(name);
			if (result == null) {
				throw new FileNotFoundException();
			} else {
				return defineClass(name, result, 0, result.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	private byte[] getClassFromCustomPath(String name) {
		//从自定义类中加载指定类：细节略
		//如果指定路径的文件字节码进行了加密，那么在这里就要进行解密
		return null;
	}

	public static void main(String[] args) {
		CustomClassLoader customClassLoader = new CustomClassLoader();
		try {
			Class<?> aClass = Class.forName("One", true, customClassLoader);
			Object o = aClass.newInstance();
			System.out.println(o.getClass().getClassLoader());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
